/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2022-08-21
 * Time: 17:19
 */


/*class Money{
    //浅克隆
    public double m = 12.5;
}*/

class Money implements Cloneable{
        //深克隆
    public double m =12.5;

    @Override
    public String toString() {
        return "Money{" +
                "m=" + m +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Animal1 implements Cloneable{

    public Money money = new Money();
    private String name;
    public int id;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //重写克隆方法用 proteected修饰访问， 不同包不能直接访问需要通过super访问

        //浅克隆
        //return super.clone();

        //深克隆
        Animal1 tmp = (Animal1) super.clone();  //克隆当前对象 即上述中得 name id
        tmp.money = (Money) this.money.clone(); //当前clone为 objet类  克隆 money
        return tmp;
        //函数结束 回收tmp
    }

    @Override
    public String toString() {
        return "Animal1{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
}



//java内置 Clonable 接口
public class Test_0821 {

                                           //throws CloneNotSupportedException 申明异常
    public static void main(String[] args) throws CloneNotSupportedException {
        Animal1 animal1 = new Animal1();
        animal1.id = 99;
        Animal1 animal11 = (Animal1) animal1.clone();  //此时为 Object类 需强转

/*        System.out.println("克隆前： "+animal1.id);
        System.out.println("克隆后： "+animal11.id);
        animal1.id = 100;
        System.out.println("===============");
        System.out.println("克隆前： "+animal1.id); // 100
        System.out.println("克隆后： "+animal11.id); // 99*/

        //浅拷贝如下：
        //两个对象都指向同一个 money。m  即 m这个对象未被单独拷贝一
/*        System.out.println("克隆前： "+animal1.money.m); // 12.5
        System.out.println("克隆后： "+animal11.money.m); // 12.5

        System.out.println("========");

        animal11.money.m = 1990.0;
        //无论修改 animal1 还是animal11 money.m  都会改变克隆后二则指向money得值

        System.out.println("克隆前： "+animal1.money.m); // 1990.0
        System.out.println("克隆后： "+animal11.money.m); // 1990.0

        System.out.println("========");

        animal1.money.m = 190;
        System.out.println("克隆前： "+animal1.money.m);  //190.0
        System.out.println("克隆后： "+animal11.money.m); //190.0*/


        //深拷贝：  让 animal11单独克隆animal1中得 money 一份

        animal1.money.m = 190;
        System.out.println("克隆前： "+animal1.money.m);  //190
        System.out.println("克隆后： "+animal11.money.m); //12.5
        System.out.println("=========");

        // animal1 和 animal11 中分别单独存了一份指向money得空间
        animal11.money.m = 10;
        System.out.println("克隆前： "+animal1.money.m);  //190
        System.out.println("克隆后： "+animal11.money.m); //10

    }
}
